package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {

        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }


    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    // 部署流程
    @Override
    @Transactional
    public void deploy(String path, String bpmnType, String info) throws FileNotFoundException {

        // 拼接路径
        // SystemConfig.getProfile() 路径 : E:/upload
        // path : /upload/2021/11/17/xxx.bpmn
        File bpmnFile = new File(SystemConfig.getProfile(),path);
        // 将流程文件部署到Activiti中
        Deployment deploy = repositoryService.createDeployment()
                .addInputStream(path, new FileInputStream(bpmnFile))
                .deploy();
        // 新建bpmnInfo 对象
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnType(bpmnType); // 设置Bpmn 类型
        bpmnInfo.setInfo(info); // 设置备注信息
        bpmnInfo.setDeploymentId(deploy.getId()); // 设置Deployment ID
        bpmnInfo.setDeployTime(new Date()); // 设置部署时间

        // 根据部署ID 创建流程定义查询对象
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .singleResult();
        // 将流程定义的名称设置到Bpmn中
        bpmnInfo.setBpmnName(definition.getName());
        bpmnInfo.setActProcessKey(definition.getKey());
        bpmnInfo.setActProcessId(definition.getId());
        // 保存到bpmnInfo 中
        bpmnInfoMapper.insert(bpmnInfo);
    }

    // 查看资源
    @Override
    @Transactional
    public InputStream readResource(String deploymentId, String type) {
        // 根据页面传过来的部署ID 创建流程定义查询对象
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
        // 忽略大小写比较
        if ("xml".equalsIgnoreCase(type)){
            // xml 资源
            // 形参 (部署ID , 定义的资源名称)
            return repositoryService.getResourceAsStream(deploymentId,definition.getResourceName());

        } else {
            // png 资源
            // 根据定义流程的id 获取 bpmnModel 对象
            BpmnModel bpmnModel = repositoryService.getBpmnModel(definition.getId());
            // 创建流程图生成器对象
            ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            // 设置生成图表的属性, 不产生乱码
            InputStream inputStream = generator.generateDiagram(bpmnModel, Collections.EMPTY_LIST, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
            // 返回生成流程图的输入流对象
            return inputStream;
        }
    }

    // 删除
    @Override
    public void delete(Long id) {
        // 根据页面传过来的 bpmnInfoId 获取BpmnInfo 对象
        BpmnInfo bpmnInfo = this.get(id);
        // 根据ID删除对应的数据
        bpmnInfoMapper.deleteByPrimaryKey(id);
        // 获取流程定义对象
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId()) // 获取流程部署ID 设置到deploymentId中
                .singleResult();

        // 删除Activiti 中的流程定义对象
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(),true);
        // 删除服务器中的文件
        // 获取流程定义的名称
        String resourceName = definition.getResourceName();
        // 拼接路径
        // SystemConfig.getProfile() 路径 : E:/upload
        // resourceName : /upload/2021/11/17/xxx.bpmn
        File file = new File(SystemConfig.getProfile(), resourceName);
        file.delete();
    }

    @Override
    public BpmnInfo queryByType(String carPackage) {
        return bpmnInfoMapper.queryByType(carPackage);
    }
}
